import { BasicComponent, ExamConfig } from "@/views/formgen/components/GenerateForm/types/form";
import { computed, inject, PropType, ref, Ref, toValue, watch } from "vue";
import { isMobile } from "@/utils/other";
import { FORM_DISABLED_KEY, IS_MOBILE_TAG_KEY } from "@/views/formgen/components/GenerateForm/types/constants";

export const formItemProps = {
  /**
   * @description 值 任意类型
   */
  value: {
    type: [Array, Object, String, Number, Boolean]
  },
  /**
   * @description 表单项配置
   */
  item: {
    type: Object as PropType<BasicComponent>
  },
  /**
   * 考试配置
   */
  examConfig: {
    type: Object as PropType<ExamConfig>
  },
  // 组件处于哪个模式
  mode: {
    type: String
  }
};

export const formEmits: string[] = ["update:value"];

export function useFormItem(props: any, emits: any, watchChangeVal = true) {
  const changeValue = <any>ref(props.value);

  const disableStyle = computed(() => {
    return disabledProp.value ? "pointer-events: none;opacity: 0.6;" : "";
  });

  const getOptions = () => {
    return props.item.config.options;
  };

  const updateValue = (val: any) => {
    emits("update:value", toValue(val));
  };

  if (watchChangeVal) {
    watch(
      () => changeValue,
      val => {
        updateValue(val);
      },
      { deep: true }
    );
  }

  watch(
    () => props.value,
    (val: any) => {
      changeValue.value = val;
    },
    {
      deep: true
    }
  );

  const config = computed(() => {
    return props.item.config;
  });

  // 获取表单的禁用状态
  const formDisabled = inject(FORM_DISABLED_KEY, false);

  const disabledProp = computed(() => {
    // 修复不受 elForm 控制禁用
    return (props.item && props.item.disabled) || toValue(formDisabled);
  });

  const isMobileTag = inject<Ref<boolean>>(IS_MOBILE_TAG_KEY, ref(isMobile()));

  return { changeValue, disableStyle, getOptions, config, disabledProp, updateValue, isMobileTag };
}
